package org.oded.logging;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Level;
import org.apache.log4j.MDC;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

public class CustomerFilter extends Filter
{
	private Map<String, Level> customerLevelMap;
	/**
	 * The threshold is in format <client name>=<Log Level>;<client name>=<Log Level>
	 */
	private String threshold;

	private Level defaultThreshold = Level.INFO;

	public CustomerFilter()
	{
		customerLevelMap = new HashMap<String, Level>();
	}

	@Override
	public int decide( LoggingEvent event )
	{
		String clientName = (String) MDC.get( CustomerFileAppender.MDC_CUSTOMER_KEY );
		// if the client name is unknown denied
		if ( clientName == null )
		{
			return Filter.DENY;
		}

		Level logLevel = customerLevelMap.get( clientName );
		if ( logLevel == null )
		{
			logLevel = defaultThreshold;
		}

		if ( event.getLevel().isGreaterOrEqual( logLevel ) )
		{
			return Filter.ACCEPT;
		}

		return Filter.DENY;
	}

	public void setThreshold( String threshold )
	{
		this.threshold = threshold;

		String[] clientLevels = threshold.split( ";" );
		for ( int i = 0 ; i < clientLevels.length ; i++ )
		{
			String clientLevel = clientLevels[i];
			String[] clientLevelPair = clientLevel.split( "=" );
			if ( clientLevelPair.length == 2 )
			{
				String clientName = clientLevelPair[0];
				Level logLevel = Level.toLevel( clientLevelPair[1], Level.INFO );
				customerLevelMap.put( clientName, logLevel );
			}
		}
	}

	public String getThreshold()
	{
		return threshold;
	}

	public void setDefaultThreshold( Level defaultThreshold )
	{
		this.defaultThreshold = defaultThreshold;
	}

	public Level getDefaultThreshold()
	{
		return defaultThreshold;
	}

}
